package com.itheima.w_util;

import com.alibaba.fastjson.JSON;
import com.itheima.autoCode.dto.CodeContext;
import com.itheima.w_dto.ColumnInfo;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EntityGenerator {
    private static  String URL = "jdbc:mysql://118.25.183.148:3306/db2024?useUnicode=true&characterEncoding=utf-8&useSSL=false";
    private static  String USER = "root";
    private static  String PASSWORD = "178121";

    public static void refreshDbInfo(CodeContext codeContext){
        URL=codeContext.getUrl();
        USER=codeContext.getUser();
        PASSWORD=codeContext.getPassword();
    }
    
    public static List<ColumnInfo> getTableColumns(String tableName) {
        List<ColumnInfo> columns = new ArrayList<>();
        
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            DatabaseMetaData metaData = conn.getMetaData();
            ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
            List<String> pkColumns = new ArrayList<>();
            while (primaryKeys.next()) {
                pkColumns.add(primaryKeys.getString("COLUMN_NAME"));
            }
            ResultSet rs = metaData.getColumns(null, null, tableName, null);
            while (rs.next()) {
                Map<String, Object> column = new HashMap<>();
                String columnName = rs.getString("COLUMN_NAME");
                column.put("columnName", columnName);
                int dataType = rs.getInt("DATA_TYPE");
                column.put("javaType", convertToJavaType(dataType));
                column.put("javaField", toCamelCase(columnName));
                column.put("columnComment", rs.getString("REMARKS"));
                column.put("isPrimaryKey", pkColumns.contains(columnName));
                
                columns.add(JSON.parseObject(JSON.toJSONString(column), ColumnInfo.class));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return columns;
    }

    public static String getTableComment(String tableName)  {
        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
            // 从 information_schema 获取指定表注释
            String sql = "SELECT TABLE_COMMENT " +
                    "FROM INFORMATION_SCHEMA.TABLES " +
                    "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?";

            try (PreparedStatement stmt = connection.prepareStatement(sql)) {
                stmt.setString(1, tableName);

                try (ResultSet rs = stmt.executeQuery()) {
                    if (rs.next()) {
                        String comment = rs.getString("TABLE_COMMENT");
                        return comment != null ? comment : "";
                    }
                }
            }
        }catch (SQLException e) {
        }

        return "";
    }


    
    private static String convertToJavaType(int sqlType) {
        switch (sqlType) {
            case Types.BIT:
            case Types.BOOLEAN:
                return "Boolean";
            case Types.TINYINT:
                return "Byte";
            case Types.SMALLINT:
                return "Short";
            case Types.INTEGER:
                return "Integer";
            case Types.BIGINT:
                return "Long";
            case Types.FLOAT:
                return "Float";
            case Types.DOUBLE:
            case Types.NUMERIC:
            case Types.DECIMAL:
                return "BigDecimal";
            case Types.CHAR:
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                return "String";
            case Types.DATE:
                return "Date";
            case Types.TIME:
                return "Time";
            case Types.TIMESTAMP:
                return "Timestamp";
            case Types.BLOB:
            case Types.BINARY:
            case Types.VARBINARY:
            case Types.LONGVARBINARY:
                return "byte[]";
            default:
                return "Object";
        }
    }

    public static String toCamelCase(String name) {
        StringBuilder result = new StringBuilder();
        String[] parts = name.split("_");
        
        for (int i = 0; i < parts.length; i++) {
            String part = parts[i];
            if (i == 0) {
                result.append(part.toLowerCase());
            } else {
                result.append(part.substring(0, 1).toUpperCase())
                      .append(part.substring(1).toLowerCase());
            }
        }
        
        return result.toString();
    }

//    public static void main(String[] args) {
//        List<Map<String, Object>> user = getTableColumns("user");
//        System.out.println(JSON.toJSONString(user));
//    }


}